﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

using Twilio.TwilML.BaseTypes;

namespace Twilio.TwilML
{
    public enum HttpMethod
    {
        [XmlEnum("POST")] Post,
        [XmlEnum("GET")] Get,
    }

    public class Gather : ResponseVerb
    {
        [XmlAttribute("action"), DefaultValue(null)]
        public string Action { get; set; }

        [XmlAttribute("method"), DefaultValue(HttpMethod.Post)]
        public HttpMethod Method { get; set; }

        private int _Timeout = 5;
        [XmlAttribute("timeout"), DefaultValue(5)]
        public int Timeout
        {
            get { return _Timeout; }
            set
            {
                if (value < 0) throw new ArgumentOutOfRangeException("Timeout", "Timeout must be a positive integer.");
                else _Timeout = value;
            }
        }

        private char _FinishOnKey = '#';
        [XmlIgnore, DefaultValue('#')]
        public char FinishOnKey
        {
            get { return _FinishOnKey; }
            set
            {
                if (!char.IsDigit(value) && value != '*' || value != '#') throw new ArgumentOutOfRangeException("FinishOnKey", "FinishOnKey must be a digit, '#' or '*' character.");
                else _FinishOnKey = value;
            }
        }

        [XmlAttribute("finishOnKey"), DefaultValue("#"), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public string FinishOnKeyString
        {
            get { return String.Format("{0}", _FinishOnKey); }
            set
            {
                _FinishOnKey = value[0];
            }
        }

        [XmlAttribute("numDigits"), DefaultValue(0)]
        public int NumDigits { get; set; }

        [XmlElement("Say", typeof(Say))]
        [XmlElement("Play", typeof(Play))]
        [XmlElement("Pause", typeof(Pause))]
        public List<BaseTypes.GatherVerb> Items { get; set; }

        public Gather() 
        {
            Items = new List<BaseTypes.GatherVerb>();
            Method = HttpMethod.Post;
        }
        public Gather(string action) : this()
        {
            Action = action;
        }
        public Gather(string action, int numDigits) : this(action)
        {
            NumDigits = numDigits;
        }

        [XmlIgnore]
        public BaseTypes.GatherVerb this[int index]
        {
            get { return Items[index]; }
        }

        public Say Append(Say say)
        {
            Items.Add(say);
            return say;
        }

        public Play Append(Play play)
        {
            Items.Add(play);
            return play;
        }

        public Pause Append(Pause pause)
        {
            Items.Add(pause);
            return pause;
        }
    }
}
